﻿using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.Extensions;
using Abp.ObjectMapping;
using Abp.Timing;
using Mt.Site.Core.WorkFlows.Enum;
using Mt.Site.Core.WorkFlows.Permissions;
using Mt.Site.Core.WorkFlows.Process;
using Mt.Site.Core.WorkFlows.Process.Entities;
using Mt.Site.Core.WorkFlows.Process.Stores;
using System;
using System.Threading.Tasks;

namespace Mt.Site.Core.WorkFlows.Diy.Actions.Impl
{
    //归档
    public class GuiDangAction : ActionBase
    {
        public override async Task<string> DisplayName(IWorkFlowManager manager)
        {
            if (DiyStaticFunction.IsApprovalFlow(manager.WorkFlow.Definition.CustomData))
            {
                //将提交拆分为 同意和 不同意
                return "通过审批";
            }
            else
            {
                return await Task.FromResult(UniqueName);
            }
        }

        public override string UniqueName => WorkFlowConst.OperationName.GuiDangAction;
        private const string RequiredPermissionName = WorkFlowPermissions.Pages_Manage_WorkFlow_GuiDang;

        private readonly IPermissionChecker _permissionChecker;

        private readonly IRepository<WorkFlowPaperArchive, Guid> _workFlowPaperArchiveRepository;
        private readonly IRepository<WorkFlowPaper, Guid> _workFlowPaperRepository;
        private readonly IObjectMapper _objectMapper;
        private readonly IUnitOfWorkManager _unitOfWorkManager;

        private readonly IWorkFlowFormDataStore _workFlowFormDataStore;

        public GuiDangAction(
            IPermissionChecker permissionChecker,
            IRepository<WorkFlowPaperArchive, Guid> workFlowPaperArchiveRepository,
            IRepository<WorkFlowPaper, Guid> workFlowPaperRepository,
            IObjectMapper objectMapper,
            IUnitOfWorkManager unitOfWorkManager,
            IWorkFlowFormDataStore workFlowFormDataStore)
        {
            _permissionChecker = permissionChecker;
            _workFlowPaperArchiveRepository = workFlowPaperArchiveRepository;
            _workFlowPaperRepository = workFlowPaperRepository;
            _objectMapper = objectMapper;
            _unitOfWorkManager = unitOfWorkManager;
            _workFlowFormDataStore = workFlowFormDataStore;
        }

        public override async Task<bool> IsShowAsync(IWorkFlowManager manager)
        {
            var actionState = await manager.CheckActionStateAsync();
            var isBranchLine = await manager.IsBranchLineAsync();
            var canOperate = manager.CanOperate(UniqueName);
            var hasNext = await manager.CanGoNextAsync();
            var hasOtherOperator = (actionState == ActionState.Todo ? await manager.IsMultiplePeopleAsync() : false);
            var isGranted = await _permissionChecker.IsGrantedAsync(RequiredPermissionName);

            //当前是待办，并且没有后续步骤
            if (isGranted
                && actionState == ActionState.Todo
                && !isBranchLine
                && !hasOtherOperator
                && canOperate
                && !hasNext)
            {
                return true;
            }
            return false;
        }

        public override async Task OperateAsync(IWorkFlowManager manager, object data)
        {
            if (await IsShowAsync(manager))
            {
                await DiyStaticFunction.TougaoFormDataCheckAsync(_workFlowFormDataStore, manager.PaperId);

                #region 办结
                await manager.WorkFlowPluginFunction.BeforeFinishedAsync(manager);
                var args = data as ActionArgs;

                //信息稿件状态切换为办结,文件状态改为发布状态
                var entity = manager.CurrentPaper.Paper;
                entity.ChangePaperState(PaperState.Finished);

                if (DiyStaticFunction.IsApprovalFlow(manager.WorkFlow.Definition.CustomData))
                {
                    entity.ChangeApprovalResult(ApprovalResult.Pass);  //同意

                    if (args.ReplyMsg.IsNullOrEmpty())
                    {
                        args.ReplyMsg = "通过";
                    }
                }

                //状态数据切换为已处理
                var current = await manager.GetCurrentProcessAsync();
                var fromName = await manager.UserAndUnitFinder.GetUserNameAsync(current.UserId);

                await manager.HasSolved(args.ReplyMsg, WorkFlowProcess.DefaultReplyMsg, MoveMode.End);
                await manager.AddLogAsync("办结", fromName, "", current?.Id);

                await manager.WorkFlowPluginFunction.AfterFinishedAsync(manager);

                #endregion

                await _unitOfWorkManager.Current.SaveChangesAsync();

                #region 归档
                await manager.WorkFlowPluginFunction.BeforeArchivedAsync(entity);
                var paperId = entity.Id;

                var newEntity = _objectMapper.Map<WorkFlowPaperArchive>(entity);
                newEntity.ArchivedOperator = fromName;
                newEntity.ArchivedTime = Clock.Now;

                await _workFlowPaperArchiveRepository.InsertAsync(newEntity);
                await _workFlowPaperRepository.DeleteAsync(paperId);

                await manager.WorkFlowPluginFunction.AfterArchivedAsync(paperId);
                #endregion
            }
        }

        public override bool NeedCheckState => false;
        public override bool NeedReply(IWorkFlowManager manager)
        {
            return false;
        }
    }
}

